package com.bailan.foreat.listener;

import com.bailan.foreat.entity.Comment;
import com.bailan.foreat.entity.Item;
import com.bailan.foreat.entity.Store;
import com.bailan.foreat.mapper.CommentMapper;
import com.bailan.foreat.mapper.ItemMapper;
import com.bailan.foreat.service.CommentService;
import com.bailan.foreat.service.ItemService;
import com.bailan.foreat.service.OrderService;
import com.bailan.foreat.vo.ItemVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class AutoEvaluationListener {
    @Autowired
    ItemService itemService;
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    CommentService commentService;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    OrderService orderService;

    @RabbitListener(queues = "autoEvaluationDeadLetterQueue")
    public void onMsg3(Integer itemId, Channel channel, Message message) throws IOException {
        System.out.println("判断: 签收后未评价,一定时间后,自动评价:");
        Item item = itemMapper.selectById(itemId);
        ItemVo itVo = itemMapper.selectItemVo(itemId);
        List<ItemVo> itemVoList = itemMapper.selectItemListOfOrderItem(item.getOrderId(),itVo.getStoreId());
        Integer userId = item.getUserId();
        // 检查item状态,item已签收,自动评价,修改状态.
        // orderItem状态(0未⽀付 1已支付,退单(按钮),签收(按钮) 2已取消 3退款中 4已退款 5已签收,评论(按钮) 6已评论)[3按钮,7状态]
        if(itemVoList.get(0).getStatus()==5) {
            List<Comment> comments = itemVoList.stream().map(itemVo -> {
                Comment comment = new Comment();
                comment.setStoreId(itemVo.getStoreId());
                comment.setProductId(itemVo.getProductId());
                comment.setContent("用户未及时作出评价，系统默认好评！");
                comment.setGrade(5);
                comment.setUserId(userId);
                comment.setItemId(itemVo.getId());
                Date createTime = new java.sql.Date(new Date().getTime());
                comment.setCreateTime(createTime);
                return comment;
            }).collect(Collectors.toList());
            String s = orderService.reviewOrderItem(comments, userId);
            System.out.println("用户未评价,系统已自动评价");
        } else {
            System.out.println("用户已评价,无需操作");
        }
        System.out.println("time-c2: "+new Date());
        //手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
